<template>
  <div>
    <!-- 添加品牌按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin-bottom:20px" @click="addShowTrademark">添加品牌
    </el-button>

    <!-- 品牌列表 -->
    <el-table :data="trademarkList" border stripe style="width: 100%;margin-bottom:20px">
      <el-table-column type="index" label="序号" width="100" align='center'>
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称">
      </el-table-column>
      <el-table-column label="品牌logo">
        <template slot-scope="scope">
          <img :src="scope.row.logoUrl" :alt="scope.row.tmName" style="width:60px;height:60px">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template slot-scope="{row}">
          <el-button size="mini" type="warning" icon="el-icon-edit" @click="updateShowTrademark(row)">修改</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteTrademark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination @size-change="handleSizeChange" @current-change="getTrademarkList" :current-page="page"
      :page-sizes="[3, 6, 9]" :page-size="limit" layout=" prev, pager, next, jumper, ->, sizes,total" :total="total"
      style="text-align:center;">
    </el-pagination>

    <!-- 添加品牌弹框 -->
    <el-dialog :title="`${formData.id? '修改' : '添加'}品牌`" :visible.sync="dialogFormVisible">
      <el-form :model="formData" style="width: 80%" :rules="rules" ref="formData">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="formData.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload class="avatar-uploader" action="dev-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTrademark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Trademark',
    data() {
      return {
        page: 1, //第几页
        limit: 3, //每页显示多少条数据
        trademarkList: [], //品管列表
        total: 0, //品牌数量
        dialogFormVisible: false,
        formData: {
          tmName: '', //品牌名称
          logoUrl: '' //图片
        },
        rules: {
          tmName: [{
              required: true,
              message: '请输入品牌名称'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
          logoUrl: [{
            required: true,
            message: '请上传图片',
            trigger: 'change'
          }]
        },
        formLabelWidth: '100px',
      }
    },
    created() {
      //代码开始创建时调用获取品牌管理列表的数据
      this.getTrademarkList();
    },
    methods: {
      //获取品牌列表
      async getTrademarkList(page = 1) {
        this.page = page; //更新页码
        let result = await this.$API.trademark.getTrademarkList(this.page, this.limit);
        if (result.code !== 200) { //判断是否获取数据成功
          this.$message.error('获取品牌信息失败'); //弹出错误信息
          return;
        }
        //更新数据
        const {
          records,
          total
        } = result.data;
        this.trademarkList = records;
        this.total = total;
      },
      //分页器---每页展示多少条
      handleSizeChange(val) {
        this.limit = val;
        this.getTrademarkList();
      },

      //图片上传成功的回调
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.formData.logoUrl = res.data; //当上传成功时,把图片地址保存下了
          //如果图片上传成功了,清理掉之前的验证信息
          this.$refs.formData.clearValidate('logoUrl');
        }
      },
      //图片的验证
      beforeAvatarUpload(file) {
        const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
        const isLt2M = file.size / 1024 / 1024 < 2;
        //限制图片的格式
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        //限制图片的大小
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //点击添加品牌
      addShowTrademark() {
        //初始化数据
        this.formData = {
          tmName: '',
          logoUrl: ''
        };
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs.formData.clearValidate();
        })
      },
      //修改品牌
      updateShowTrademark(trademarkInfo) {
        //防止同步修改
        this.formData = {
          ...trademarkInfo
        };
        this.dialogFormVisible = true;
      },
      //添加或者修改的操作
      addOrUpdateTrademark() {
        //点击确定按钮需要进行表单验证
        this.$refs.formData.validate(async (valid) => {
          if (valid) {
            let result = await this.$API.trademark.addOrUpdate(this.formData);
            if (result.code !== 200) {
              this.$message.error('操作失败');
              return;
            }
            this.$message.success('操作成功');
            //如果是修改操作则刷新的是当前页数据,如果是添加操作,则刷新的是第一页数据
            this.getTrademarkList(this.formData.id ? this.page : 1);
            this.dialogFormVisible = false;
          }
        })
      },
      //删除品牌
      deleteTrademark(trademarkInfo) {
        this.$confirm(`此操作将永久删除${trademarkInfo.tmName}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.$API.trademark.deleteTrademarkById(trademarkInfo.id); //调用删除的接口
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          //重新获取数据，如果删除前此页只有一条数据，就获取上一页
          this.getTrademarkList(this.trademarkList.length === 1 && this.page > 1 ? this.page - 1 : this.page);
        }).catch((error) => {
          if (error == 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
            return;
          }
          this.$message.error(error);
        });
      }
    }
  }

</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>
